<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>贪玩蓝月-大厅</title>
</head>
<body>
    <hr/>
    <div id="message" style="overflow:auto;height: 300px;color: #0F0;background-color: #000;"></div>
    <hr/>
    <input id="name" type="text" value="#(name??'渣渣辉')"/>
    <button onclick="setName()">昵称</button>
    <hr/>
    <textarea id="text" rows="5" cols="">大家好~我是#(name??'渣渣辉')！</textarea>
    <button onclick="send()">发送</button>
    <hr/>
    <button onclick="setName()" type="button">上线</button>
    <button onclick="closeWebSocket()" type="button">下线</button>
</body>

<script src="https://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    var websocket = null;
    
    function setName(){
    	var name = $("#name").val();
    	var host = window.location.host;//+window.location.pathname;
    	console.log(new Date(), name , " 上线");
    	$.getJSON("/getwebsocket", { "name": name, "host": host }, function(ret){
            if(ret.state == "ok") {
           	    newWebSocket(ret.url);
            }else{
                alert('抱歉，失败')
            }
        });
    }
    
    function newWebSocket(url){
	    if ('WebSocket' in window) {
	        websocket = new WebSocket(url);
	    } else {
	        alert('请使用火狐或谷歌浏览器')
	        return;
	    }
	    //连接发生错误的回调方法
	    websocket.onerror = function () {
	        setMessageInnerHTML("离线");
	    }

	    //连接成功建立的回调方法
	    websocket.onopen = function () {
	        setMessageInnerHTML("上线");
	    }

	    //接收到消息的回调方法
	    websocket.onmessage = function (event) {
	        setMessageInnerHTML(event.data);
	    }

	    //连接关闭的回调方法
	    websocket.onclose = function () {
	        setMessageInnerHTML("下线");
	    }

    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        var e = document.getElementById('message');
        e.innerHTML += innerHTML + '<br/><br/>';
        e.scrollTop = e.scrollHeight;
    }
    
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        if(websocket != null){
	    	websocket.close();
        }
    }

    //发送消息
    function send() {
    	if(websocket == null){
    		setName();
    		return;
    	}
        var message = document.getElementById('text').value;
        websocket.send(message);
    }

</script>
</html>